<template>
  <div class="upload-container">
    <el-upload
      :name="name"
      :data="dataObj"
      :multiple="false"
      :show-file-list="false"
      :on-success="handleImageSuccess"
      class="image-uploader"
      :action="action"
      :accept="accept"
      v-loading="loading"
      :before-upload="beforeUpload"
      :on-error="handleError"
    >
      <!-- <i class="el-icon-upload" /> -->
      <el-image v-if="tempUrl" :src="tempUrl" class="avatar" />
      <cImage v-else-if="imageUrl" :imageId="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { singleUploadApi } from '@/api/file'
import { getToken } from '@/utils/auth';
import cImage from '@/components/Image';
import videoIcon from '@/assets/20210312104723557296444874187250.png';

export default {
  name: 'SingleImageUpload',
  components: { cImage },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: [String, undefined],
      default: ''
    },
    accept: {
      type: [String, undefined],
      default: 'image/*'
    }
  },
  data() {
    return {
      name: '',
      tempUrl: '',
      dataObj: { token: getToken() },
      action: singleUploadApi,
      loading: false
    }
  },
  computed: {
    imageUrl() {
      // if (this.value && this.value.indexOf('/') > -1) return this.value;
      return this.value
    }
  },
  methods: {
    rmImage() {
      this.emitInput('')
    },
    emitInput(val) {
      this.$emit('change', val)
    },
    handleImageSuccess(res, file) {
      this.loading = false;
      this.emitInput(res.data.fileId);
      if (!file.raw.type.startsWith('image/')) this.tempUrl = videoIcon;
    },
    beforeUpload() {
      this.tempUrl = '';
      this.loading = true;
      return true;
    },
    handleError() {
      this.loading = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.image-uploader {
  width: 180px;
}
.image-uploader ::v-deep {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .el-upload:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
}
</style>
